package com.xoms.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xoms.admin.controller.res.bean.RProPureBackBean;
import com.xoms.admin.controller.res.bean.RProPureBackInfoBean;
import com.xoms.admin.model.AccountBean;
import com.xoms.admin.model.AuditBean;
import com.xoms.admin.model.ProPureBackBean;
import com.xoms.admin.model.ProPureBackInfoBean;
import com.xoms.admin.model.vo.BatchPureBackBean;
import com.xoms.admin.persist.dao.ProAuditDao;
import com.xoms.admin.persist.dao.ProPureBackDao;
import com.xoms.admin.service.ProPureBackService;
import com.xoms.admin.service.exception.ServiceException;
import com.xoms.admin.service.res.PageResult;
import com.xoms.util.AppTextUtil;
import com.xoms.util.DateTimeUtil;
import com.xoms.util.NumUtil;
import com.xoms.util.StringUtil;

@Service
public class ProPureBackServiceImpl implements  ProPureBackService {
	
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	ProPureBackDao proPureBackImpl;
	
	@Autowired
	ProAuditDao proAuditImpl;

	@Override
	public PageResult<RProPureBackBean> getPureBacks(AccountBean account, int page, int pageSize, String startTime,
			String endTime, String storeHouseId) {
		PageResult<RProPureBackBean> result = new PageResult<RProPureBackBean>();
		List<RProPureBackBean> resList = new ArrayList<RProPureBackBean>();
		// 获取退货数量
		int count = proPureBackImpl.selectCount(startTime, endTime, storeHouseId);
		if(count > 0) {
			//查询退货列表
			List<ProPureBackBean> lists = proPureBackImpl.selectList(page, pageSize, startTime, endTime, storeHouseId);

			if (lists != null) {
				RProPureBackBean rb = null;
				for (ProPureBackBean pb : lists) {
					rb=parse(pb);
					resList.add(rb);
				}
			}
		}
		
		result.setData(resList);
		result.setCount(count);
		return result;
	}

	/**
	 * 格式化数据
	 * @param acc
	 * @return
	 */
	private RProPureBackBean parse(ProPureBackBean pro) {
		RProPureBackBean res = new RProPureBackBean();
		res.setAccount(pro.getAccount());
		res.setAccountId(pro.getAccount());
		res.setPid(pro.getPid());
		res.setPurchaseId(pro.getPurchaseId());
		res.setPurchaseNo(pro.getPurchaseNo());
		res.setPureBackNo(pro.getPureBackNo());
		res.setRemark(pro.getRemark());
		res.setReview(pro.getReview());
		res.setStatus(pro.getStatus());
		res.setStoreHouse(pro.getStoreHouse());
		res.setStoreHouseId(pro.getStoreHouseId());
		res.setCreateTime(DateTimeUtil.formatTimestamp(pro.getCreateTime()));
		return res;
	}
	
	@Override
	public PageResult<RProPureBackInfoBean> getPureBackDetails(AccountBean account, String key, int page, int pageSize,
			String pid, int paging) {
		PageResult<RProPureBackInfoBean> result = new PageResult<RProPureBackInfoBean>();
		List<RProPureBackInfoBean> resList = new ArrayList<RProPureBackInfoBean>();
		int count = proPureBackImpl.selectDetailCount(pid, key);
		if(count > 0) {
			//查询退货单列表
			List<ProPureBackInfoBean> lists = proPureBackImpl.selectDetailList(pid, key, page, pageSize, paging);
			if (lists != null) {
				RProPureBackInfoBean rb = null;
				for (ProPureBackInfoBean br : lists) {
					rb = new RProPureBackInfoBean();
					rb = parseDetail(br);
					resList.add(rb);
				}
			}
		}
		result.setData(resList);
		result.setCount(count);
		return result;
	}

	/**
	 * 格式化详情
	 * @param pur
	 * @return
	 */
	private RProPureBackInfoBean parseDetail(ProPureBackInfoBean br) {
		RProPureBackInfoBean res = new RProPureBackInfoBean();
		res.setCategory(br.getCategory());
		res.setNumber(br.getNumber());
		res.setPrice(br.getPrice());
		res.setProduct(br.getProduct());
		res.setProductBar(br.getProductBar());
		res.setProductId(br.getProductId());
		res.setUnit(br.getUnit());
		res.setPureBackId(br.getPureBackId());
		return res;
	}
	
	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public RProPureBackBean edit(AccountBean account, String pid, String purchaseId, String remark, String details,
			int isSubmit) {
		boolean flag = false;
		ProPureBackBean data = new ProPureBackBean();
		data.setPurchaseId(purchaseId);
		data.setRemark(remark);
		
		if (StringUtil.isEmpty(pid)) {// 新建
			pid = AppTextUtil.getPrimaryKey();// id
			data.setPid(pid);
			data.setAccountId(account.getAccid());
			data.setStatus(isSubmit);// 未提交审核

			// 采购编号：BS + YYYYMMDDHHmm + 0000001;一年百万数据？
			String maxNo = proPureBackImpl.selectMaxNoInYear();// 获取当年报损单最大数量
			int num = 0;
			if(!StringUtil.isEmpty(maxNo)) {
				num = NumUtil.toInt(maxNo.substring(maxNo.length() - 7, maxNo.length()), 0);
			}
			String pureNo = AppTextUtil.getRandomProNo("TH", (num + 1), 7);
			data.setPureBackNo(pureNo);

			flag = proPureBackImpl.insert(data) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","报损订单");
			}
			if(isSubmit == 2) { // 直接提交审核

				flag = submitAudit(account, pid, 5);
			}
			
		} else {
			data.setPid(pid);
			flag = proPureBackImpl.update(data) > 0;// 更新数据库
			if (!flag) {
				throw new ServiceException("database_update_fail","采购订单");
			}
		}
		// 将采购商品详情信息批量更新到数据库
		if(!StringUtil.isEmpty(details)) { 
			flag = replaceBatchDetail(pid, details);
		}
		ProPureBackBean res = proPureBackImpl.selectOneById(pid);
		return parse(res);
	}

	private boolean replaceBatchDetail(String pid, String details) {
		boolean flag = false;
		// JSON转list
		List<BatchPureBackBean> batch = JSON.parseArray(details, BatchPureBackBean.class);
		for(BatchPureBackBean pureback : batch) {
			pureback.setPureBackId(pid);
		}
		if(batch.size() > 0) {
			// 删除历史记录，
			// 判断数量
			int detailCount = proPureBackImpl.selectDetailCount(pid, null);
			if(detailCount > 0) {
				// 删除当前采购单下所有关联采购单详情
				flag = proPureBackImpl.delDetails(pid) > 0;
				if (!flag) {
					throw new ServiceException("database_delete_fail", "报损单详情");
				}
			}
			// 批量更新
			flag = proPureBackImpl.replaceBatchDetail(batch) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","报损详情");
			}
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public boolean del(AccountBean account, String pid) {
		boolean flag = false;
		// 删除退货前判断是否已提交，提交的退货单不能删除
		ProPureBackBean breakage = proPureBackImpl.selectOneById(pid);
		if(breakage == null) {// 退货单不存在
			throw new ServiceException("object_is_not_exist","退货单");
		}
		int status = NumUtil.toInt(breakage.getStatus(), 1);
		if(status != 1) {
			throw new ServiceException("object_is_submit", "退货单");
		}
		
		flag = proPureBackImpl.del(pid) > 0;
		if (!flag) {
			throw new ServiceException("database_delete_fail", "退货单");
		}
		// 判断数量
		int detailCount = proPureBackImpl.selectDetailCount(pid, null);
		if(detailCount > 0) {
			// 删除当前退货单下所有关联退货单详情
			flag = proPureBackImpl.delDetails(pid) > 0;
			if (!flag) {
				throw new ServiceException("database_delete_fail", "退货单详情");
			}
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public boolean submitPureBack(AccountBean account, String pid) {
		boolean flag = false;
		// 提交退货单前判断是否是待提交状态，提交的退货单不能多次提交
		ProPureBackBean breakage = proPureBackImpl.selectOneById(pid);
		if(breakage == null) {// 退货单不存在
			throw new ServiceException("object_is_not_exist","退货单");
		}
		int status = breakage.getStatus();
		if(status != 1 && status != 4) {
			throw new ServiceException("object_is_not_unsubmit", "退货单");
		}
		flag = proPureBackImpl.updateSubmitStatus(pid, 2) > 0;// 更新退货单状态,1提交待审核
		if (!flag) {// 更新状态失败
			throw new ServiceException("database_update_fail","退货审核状态");
		}
		flag = submitAudit(account, pid, 5);
		return flag;
	}
	
	private boolean submitAudit(AccountBean account, String targetId, int type) {
		boolean flag;
		AuditBean audit = new AuditBean();// 添加到审核表
		audit.setAid(AppTextUtil.getPrimaryKey());
		audit.setSubmitId(account.getAccid());
		audit.setType(type);// 审核类型：1采购2入库3盘库4损耗5充公6冲正7退货到供应商
		audit.setTargetId(targetId);// 关联id
		// 审核编号：SH+ YYYYMMDDHHmm + 0000001;一年百万数据？
		String maxNo = proAuditImpl.selectMaxAuditNoInYear(type);// 获取当年审核单最大数量
		int num = 0;
		if(!StringUtil.isEmpty(maxNo)) {
			num = NumUtil.toInt(maxNo.substring(maxNo.length() - 7, maxNo.length()), 0);
		}
		String auditNo = AppTextUtil.getRandomProNo("SH", (num + 1), 7);
		audit.setAuditNo(auditNo);
		audit.setStatus(0);
		
		flag = proAuditImpl.insert(audit) > 0;
		if (!flag) {// 插入状态失败
			throw new ServiceException("database_insert_fail","退货审核提交");
		}
		return flag;
	}

}
